//
//  RegisterViewController.m
//  Btpin
//
//  Created by Vic on 2019/4/3.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "RegisterViewController.h"
#import "UILabel+YBAttributeTextTapAction.h"
#import "SigninAccountViewController.h"
#import "IDSelectViewController.h"
#import "AppDelegate.h"
#import "PersonalTabBarController.h"
#import "CompanyTabBarController.h"
//#import "ResignAgreementViewController.h"
#import "GeneralWebViewViewController.h"

#import "ShareItemButton.h"
#import "WXBindingViewController.h"
#import "WXAuth.h"

#import "AESEnrypt.h"
#import "NSString+AES.h"
#import "TUIKit.h"
#import "CountryCodeViewController.h"

@interface RegisterViewController ()<UITextFieldDelegate>
{
//    UIButton *countryCodeBtn;
    UITextField *phoneTextField;
    UITextField *captchaTextField;
    UITextField *passwordTextField;
    
    UIButton *captchaButton;
    NSInteger timerInt;
    
    NSString *recordStr;
    
    NSString *countryCodeStr;
}
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation RegisterViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [DataToolsControl sharedManager].openSigninType = OpenSigninTypeOfWXRegister;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
//    countryCodeStr = @"86";
    countryCodeStr = @"";
    recordStr = @"";
    timerInt = CaptchaTime;
    [self initUI];
    
    [DataToolsControl sharedManager].appJustOpen = NO;
}
- (void)countryCodeBtnTap {
    CountryCodeViewController *CCVC = [[CountryCodeViewController alloc] init];
    CCVC.selectCode = ^(NSString * _Nonnull code) {
        self->countryCodeStr = code;
//        [self->countryCodeBtn setTitle:[NSString stringWithFormat:@"+ %@", code] forState:UIControlStateNormal];
    };
    [self.navigationController pushViewController:CCVC animated:YES];
}
- (void)initUI {
    self.navigationItem.title = @"注册";
    
//    countryCodeBtn = [UIToolsControl initButtonWithFrame:CGRectMake(ScalePS(20), ScalePS(25), ScalePS(50), ScalePS(50)) imageName:nil target:self action:@selector(countryCodeBtnTap) title:[NSString stringWithFormat:@"+ %@", countryCodeStr] titleColor:THEMECOLOR_OF_TEXT_333333];
//    countryCodeBtn.titleLabel.font = Font(Font_15);
//    countryCodeBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
//    countryCodeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//    [self.view addSubview:countryCodeBtn];
    
//    phoneTextField = [UIToolsControl initTextFieldWithFrame:CGRectMake(EndX(countryCodeBtn)+10*Scale, 25*Scale, WIDTH-60*Scale-ScalePS(50), 50*Scale) placeholder:PhoneNumberPlaceholderText secureTextEntry:NO font:Font_17 padding:YES];
    phoneTextField = [UIToolsControl initTextFieldWithFrame:CGRectMake(ScalePS(30), 25*Scale, WIDTH-60*Scale, 50*Scale) placeholder:PhoneNumberPlaceholderText secureTextEntry:NO font:Font_17 padding:YES];
    [phoneTextField borderColor:THEMECOLOR_OF_TEXT_cccccc borderWidth:lineH borderType:BorderSideTypeBottom];
    phoneTextField.delegate = self;
    phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:phoneTextField];
    
    captchaTextField = [UIToolsControl initTextFieldWithFrame:CGRectMake(30*Scale, EndY(phoneTextField)+25*Scale, WIDTH-150*Scale, 50*Scale) placeholder:CaptchaPlaceholderText secureTextEntry:NO font:Font_17 padding:YES];
    captchaTextField.delegate = self;
    captchaTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:captchaTextField];
    UIView *lineView = [UIToolsControl initViewWithFrame:CGRectMake(30*Scale, EndY(captchaTextField)-1, WIDTH-60*Scale, lineH) backgroundColor:THEMECOLOR_OF_TEXT_cccccc];
    [self.view addSubview:lineView];
    captchaButton = [UIToolsControl initButtonWithFrame:CGRectMake(WIDTH-120*Scale, EndY(phoneTextField)+30*Scale, 100*Scale, 40*Scale) imageName:nil target:self action:@selector(sendCaptchaBtnTap) title:@"发送验证码" titleColor:THEMECOLOR_OF_TEXT_333333];
    captchaButton.titleLabel.font = Font(Font_14);
    [self.view addSubview:captchaButton];
    
    passwordTextField = [UIToolsControl initTextFieldWithFrame:CGRectMake(30*Scale, EndY(captchaButton)+25*Scale, WIDTH-60*Scale, 50*Scale) placeholder:PasswordSetPlaceholderText secureTextEntry:YES font:Font_17 padding:YES];
    [passwordTextField borderColor:THEMECOLOR_OF_TEXT_cccccc borderWidth:lineH borderType:BorderSideTypeBottom];
    passwordTextField.delegate = self;
    passwordTextField.keyboardType = UIKeyboardTypeNamePhonePad;
    [self.view addSubview:passwordTextField];
    
    UIButton *okBtn = [UIToolsControl initButtonWithFrame:CGRectMake(40*Scale, EndY(passwordTextField)+70*Scale, WIDTH-80*Scale, 46*Scale) imageName:nil target:self action:@selector(okBtnTap) title:@"立即注册" titleColor:COLOR_OF_WHITE];
    okBtn.titleLabel.font = FontBold(Font_17);
    okBtn.backgroundColor = THEMECOLOR_OF_ORANGE;
    okBtn.layer.cornerRadius = 23*Scale;
    okBtn.layer.masksToBounds = YES;
    [self.view addSubview:okBtn];
    
    UIButton *accountBtn = [UIToolsControl initButtonWithFrame:CGRectMake(StartX(okBtn), EndY(okBtn)+10*Scale, 120*Scale, 40*Scale) imageName:nil target:self action:@selector(accountBtnTap) title:@"账号密码登录" titleColor:THEMECOLOR_OF_TEXT_333333];
    accountBtn.titleLabel.font = Font(Font_14);
    [self.view addSubview:accountBtn];
    
    CGFloat itemWidth = (WIDTH-20*Scale)*0.25;
//    ShareItemButton *wxSigninBtn = [[ShareItemButton alloc] initWithFrame:CGRectMake((WIDTH-itemWidth)*0.5, EndY(accountBtn)+100*Scale, itemWidth, 120*Scale) imageName:@"share_weixin_haoyou" itemText:@"微信登录"];
    ShareItemButton *wxSigninBtn = [[ShareItemButton alloc] initWithFrame:CGRectMake((WIDTH-itemWidth)*0.5, HEIGHT-HeightOfStatusBarAndNavigationBar-SIMEmojKeyBoardkBottomNOSafeArea_Height-200*Scale, itemWidth, 120*Scale) imageName:@"share_weixin_haoyou" itemText:@"微信登录"];
    [wxSigninBtn addTarget:self action:@selector(wxSigninBtnTap) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:wxSigninBtn];
    if (![UIToolsControl canOpenWXApp]) {
        wxSigninBtn.hidden = YES;
    }
    
    
    NSString *clauseString = @"注册即代表您已同意我们的《服务协议》和《隐私政策》";
    CGFloat clauseStrWidth = [UIToolsControl textWidth:clauseString size:CGSizeMake(MAXFLOAT, 40*Scale) font:Font_13]+1;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:clauseString];
    [attributedString addAttribute:NSFontAttributeName value:Font(Font_13) range:NSMakeRange(0, clauseString.length)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:THEMECOLOR_OF_TEXT_666666 range:NSMakeRange(0, clauseString.length)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:THEMECOLOR_OF_ORANGE range:NSMakeRange(12, 13)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:THEMECOLOR_OF_TEXT_666666 range:NSMakeRange(18, 1)];
    UILabel *clauseLabel = [[UILabel alloc] initWithFrame:CGRectMake((WIDTH-clauseStrWidth)*0.5, HEIGHT-HeightOfStatusBarAndNavigationBar-SIMEmojKeyBoardkBottomNOSafeArea_Height-60*Scale, clauseStrWidth, 40*Scale)];
    clauseLabel.font = Font(Font_13);
    clauseLabel.backgroundColor = COLOR_OF_CLEAR;
    clauseLabel.attributedText = attributedString;
    clauseLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:clauseLabel];
    [clauseLabel yb_addAttributeTapActionWithStrings:@[@"《服务协议》", @"《隐私政策》"] tapClicked:^(NSString *string, NSRange range, NSInteger index) {
        GeneralWebViewViewController *GWVC = [[GeneralWebViewViewController alloc] init];
        if ([string isEqualToString:@"《服务协议》"]) {
            NSLog(@"服务协议");
            GWVC.showType = GeneralWebViewTypeOfResignAgreement;
        } else {
            NSLog(@"隐私政策");
            GWVC.showType = GeneralWebViewTypeOfPrivacyPolicy;
        }
        GWVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:GWVC animated:YES];
    }];
    
    
//    UIButton *accountBtn = [UIToolsControl initButtonWithFrame:CGRectMake(20*Scale, HEIGHT-HeightOfStatusBarAndNavigationBar-HeightOfTabBarSafeMargin-70*Scale, 120*Scale, 40*Scale) imageName:nil target:self action:@selector(accountBtnTap) title:@"账号密码登录" titleColor:THEMECOLOR_OF_TEXT_333333];
//    accountBtn.titleLabel.font = Font(Font_15);
//    [self.view addSubview:accountBtn];
}
- (void)wxSigninBtnTap {
    [WXAUTH sendWXAuthReq];
}
- (void)notificationWXCode:(NSNotification *)notification {
    if ([DataToolsControl sharedManager].openSigninType != OpenSigninTypeOfWXRegister) {
        return;
    }
    NSString *code = [NSString stringWithFormat:@"%@", notification.userInfo[@"code"]];
    NSLog(@"%@", code);
    
    if (![code isEqualToString:UD_GetOForK(isOpenWXSigninCode)]) {
        return;
    }
    if ([DataToolsControl sharedManager].codeRecord != 1) {
        return;
    }
    [DataToolsControl sharedManager].codeRecord++;
    
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    if([DataToolsControl sharedManager].isApple){
        [dic setObject:@"apple" forKey:@"type"];
    }else{
        [dic setObject:@"weixin" forKey:@"type"];
    }
    [dic setObject:code forKey:@"code"];
    [dic setObject:@"" forKey:@"token"];
    
    [BaseNetManager requestWithMethod:POST path:User_OpenSignin_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDDismiss;
            id data = responseObject[@"data"];
            if ([data isKindOfClass:[NSDictionary class]] && [data count]) {
//                [self detailDataAndPushVC:responseObject];
                
                [DataToolsControl autoLogin];
            } else {
                WXBindingViewController *WXBVC = [[WXBindingViewController alloc] init];
                [self.navigationController pushViewController:WXBVC animated:YES];
            }
        } else {
            NSString *str = [NSString stringWithFormat:@"%@", responseObject[@"msg"]];
            SVPHUDError(str);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)okBtnTap {
    [UIToolsControl resignFirstResponderForTextFieldArray:@[phoneTextField, passwordTextField, captchaTextField]];
    if (phoneTextField.text.length>0) {
        if ([UIToolsControl validatePhoneNumber:phoneTextField.text]) {
            if (captchaTextField.text.length>=0) {
                [self upDate];
//                if ([UIToolsControl validateNumber:captchaTextField.text]) {
//                    if (passwordTextField.text.length) {
//                        [self upDate];
//                    } else {
//                        SVPHUDError(PasswordAlertText);
//                        [passwordTextField becomeFirstResponder];
//                    }
//                } else {
//                    SVPHUDError(CaptchaOKAlertText);
//                    [captchaTextField becomeFirstResponder];
//                }
            } else {
                SVPHUDError(CaptchaAlertText);
                [captchaTextField becomeFirstResponder];
            }
        } else {
            SVPHUDError(PhoneNumberOKAlertText);
            [phoneTextField becomeFirstResponder];
        }
    } else {
        SVPHUDError(PhoneNumberAlertText);
        [phoneTextField becomeFirstResponder];
    }
}
- (void)upDate {
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:phoneTextField.text forKey:@"mobile"];
    [dic setObject:captchaTextField.text forKey:@"verify_code"];
    
    recordStr = [passwordTextField.text aci_encryptWithAES];
    [dic setObject:recordStr forKey:@"password"];
    
//    [dic setObject:countryCodeStr forKey:@"country_code"];
    
    [BaseNetManager requestWithMethod:POST path:Register_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDSuccess(responseObject[@"msg"]);
            self->passwordTextField.text = nil;

            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD setMinimumDismissTimeInterval:1.5];
            [SVProgressHUD showSuccessWithStatus:@"注册成功"];
            [SVProgressHUD dismissWithDelay:1.5 completion:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
//            IDSelectViewController *IDSVC = [[IDSelectViewController alloc] init];
//            [self.navigationController pushViewController:IDSVC animated:YES];
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)signinLoadData:(NSDictionary *)responseObject {
    [DataToolsControl dataAnalysisUserInfo:responseObject];
    IDSelectViewController *IDSVC = [[IDSelectViewController alloc] init];
    [self.navigationController pushViewController:IDSVC animated:YES];
    
    [[TUIKit sharedInstance] initKit:[UD_GetOForK(isIMAppID) integerValue] accountType:UD_GetOForK(isIMAccountType) withConfig:[TUIKitConfig defaultConfig]];
    TIMLoginParam *login_param = [[TIMLoginParam alloc ]init];
    // identifier 为用户名，userSig 为用户登录凭证
    // appidAt3rd 在私有帐号情况下，填写与 sdkAppId 一样
    login_param.identifier = UD_GetOForK(isUserID);
    login_param.userSig = UD_GetOForK(isIMUserSig);
    login_param.appidAt3rd = UD_GetOForK(isIMAppID);
    [[TIMManager sharedInstance] login: login_param succ:^(){
        [DataToolsControl sharedManager].isTIMLoginSuccess = YES;
        NSLog(@"Init Succ");
        //                if ([DataToolsControl sharedManager].deviceToken && [DataToolsControl sharedManager].deviceToken.length) {
        NSData *tokenData = UD_GetOForK(isDeviceToken);
        if (tokenData && tokenData.length) {
            TIMTokenParam *param = [[TIMTokenParam alloc] init];
#if DEBUG
            param.busiId = TIMPushDevID;
#else
            param.busiId = TIMPushReleaseID;
#endif
//                    [param setToken:[DataToolsControl sharedManager].deviceToken];
            [param setToken:UD_GetOForK(isDeviceToken)];
            [[TIMManager sharedInstance] setToken:param succ:^{
                NSLog(@"-----> 上传 token 成功 ");
            } fail:^(int code, NSString *msg) {
                NSLog(@"-----> 上传 token 失败 ");
            }];
        }
    } fail:^(int code, NSString * err) {
        [DataToolsControl sharedManager].isTIMLoginSuccess = NO;
        NSLog(@"Login Failed: %d->%@", code, err);
    }];
    return;
    
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:phoneTextField.text forKey:@"username"];
    [dic setObject:recordStr forKey:@"password"];
    
    [BaseNetManager requestWithMethod:POST path:Signin_Pwd_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            [DataToolsControl dataAnalysisUserInfo:responseObject];
            
            IDSelectViewController *IDSVC = [[IDSelectViewController alloc] init];
            [self.navigationController pushViewController:IDSVC animated:YES];
            
            [[TUIKit sharedInstance] initKit:[UD_GetOForK(isIMAppID) integerValue] accountType:UD_GetOForK(isIMAccountType) withConfig:[TUIKitConfig defaultConfig]];
            TIMLoginParam *login_param = [[TIMLoginParam alloc ]init];
            // identifier 为用户名，userSig 为用户登录凭证
            // appidAt3rd 在私有帐号情况下，填写与 sdkAppId 一样
            login_param.identifier = UD_GetOForK(isUserID);
            login_param.userSig = UD_GetOForK(isIMUserSig);
            login_param.appidAt3rd = UD_GetOForK(isIMAppID);
            [[TIMManager sharedInstance] login: login_param succ:^(){
                [DataToolsControl sharedManager].isTIMLoginSuccess = YES;
                NSLog(@"Init Succ");
//                if ([DataToolsControl sharedManager].deviceToken && [DataToolsControl sharedManager].deviceToken.length) {
                NSData *tokenData = UD_GetOForK(isDeviceToken);
                if (tokenData && tokenData.length) {
                    TIMTokenParam *param = [[TIMTokenParam alloc] init];
#if DEBUG
                    param.busiId = TIMPushDevID;
#else
                    param.busiId = TIMPushReleaseID;
#endif
//                    [param setToken:[DataToolsControl sharedManager].deviceToken];
                    [param setToken:UD_GetOForK(isDeviceToken)];
                    [[TIMManager sharedInstance] setToken:param succ:^{
                        NSLog(@"-----> 上传 token 成功 ");
                    } fail:^(int code, NSString *msg) {
                        NSLog(@"-----> 上传 token 失败 ");
                    }];
                }
            } fail:^(int code, NSString * err) {
                [DataToolsControl sharedManager].isTIMLoginSuccess = NO;
                NSLog(@"Login Failed: %d->%@", code, err);
            }];
        }
    } failurBlock:^(NSError *error) {
        [self signinLoadData:@{}];
    }];
}
- (void)accountBtnTap {
    NSLog(@"accountBtnTap");
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)sendCaptchaBtnTap {
    NSLog(@"sendCaptchaBtnTap");
    if (phoneTextField.text.length>0) {
        if ([UIToolsControl validatePhoneNumber:phoneTextField.text]) {
            SVPHUDShow;
            __weak __typeof(self)weakSelf = self;
            [UIToolsControl getCaptcha:phoneTextField.text countryCode:countryCodeStr type:[UIToolsControl getCaptchaType:GetCaptchaTypeOfRegister] successBlock:^(id response) {
                __strong __typeof(weakSelf)strongSelf = weakSelf;
                if ([response[@"code"] integerValue] == 2000) {
                    SVPHUDSuccess(response[@"msg"]);
                    [self->captchaTextField becomeFirstResponder];
                    strongSelf.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerClick) userInfo:nil repeats:YES];
                } else {
                    SVPHUDError(response[@"msg"]);
                }
            }];
        } else {
            SVPHUDError(PhoneNumberOKAlertText);
        }
    } else {
        SVPHUDError(PhoneNumberAlertText);
        [phoneTextField becomeFirstResponder];
    }
}
- (void)timerClick {
    timerInt--;
    if (timerInt>0) {
        [captchaButton setTitleColor:THEMECOLOR_OF_TEXT_cccccc forState:UIControlStateNormal];
        [captchaButton setTitle:[NSString stringWithFormat:@"%ldS", (long)timerInt] forState:UIControlStateNormal];
        captchaButton.userInteractionEnabled = NO;
    } else {
        [captchaButton setTitle:GetCaptchaText forState:UIControlStateNormal];
        [captchaButton setTitleColor:THEMECOLOR_OF_TEXT_333333 forState:UIControlStateNormal];
        captchaButton.userInteractionEnabled = YES;
        timerInt = CaptchaTime;
        [self.timer invalidate];
        self.timer = nil;
    }
}
- (void)customBackButtonTap {
    [self.navigationController popViewControllerAnimated:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

@end
